package cn.edu.zucc.online_market.control;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;

import cn.edu.zucc.online_market.online_marketUtil;
import cn.edu.zucc.online_market.itf.IUserManager;
import cn.edu.zucc.online_market.model.BeanAddress;
import cn.edu.zucc.online_market.model.BeanProductInCart;
import cn.edu.zucc.online_market.model.BeanOrder;
import cn.edu.zucc.online_market.model.BeanProduct;
import cn.edu.zucc.online_market.model.BeanUser;
import cn.edu.zucc.online_market.util.BaseException;
import cn.edu.zucc.online_market.util.BusinessException;
import cn.edu.zucc.online_market.util.DBPool;
import cn.edu.zucc.online_market.util.DBUtil;
import cn.edu.zucc.online_market.util.DbException;
import javassist.bytecode.analysis.Type;

public class UserManager implements IUserManager{

	
	
	//unfinished method
	@Override
	public BeanOrder createOrder() throws BaseException {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void setAddress(BeanOrder order, BeanAddress address) throws BaseException {
		// TODO Auto-generated method stub
		
	}

	@Override
	// half finished
	public BeanOrder settle(BeanAddress selected_address) throws BaseException {
		// TODO Auto-generated method stub
		BeanOrder order = new BeanOrder();
		Connection conn = null;
		BeanProductInCart p=null;
		// insert value 
		int order_id = -1;
		int user_id = BeanUser.currentLoginUser.getUser_id();
		int address_id = -1;
		float original_amount = 0,settle_amount = 0;
		// int coupon_id =-1;
		// Date arrival_time = null;
		String order_state = null;
		ArrayList<BeanProductInCart> list_cart = new ArrayList<BeanProductInCart>();
		for(int i=0;i<BeanUser.currentCart.size();i++) {
			p = BeanUser.currentCart.get(i);
			if(p.isCart_selected()) list_cart.add(p);
		}
		
		try {
			conn = DBPool.getInstance().getConnection();
			conn.setAutoCommit(false);
			String sql;
			java.sql.PreparedStatement pst;
			java.sql.ResultSet rs;
			//get total amount;
			for(int i=0;i<list_cart.size();i++) {
				p = list_cart.get(i);
				original_amount = original_amount + p.getPrice() * p.getCart_product_count();
			}
			// calu discount and get settle_amount skip now,
			settle_amount = original_amount;
			//
			//insert order into user_order;
			
			sql = "select max(order_id) from user_order; ";
			pst = conn.prepareStatement(sql);
			rs = pst.executeQuery();
			if(rs.next()) {
				order_id = rs.getInt(1);
			}else {
				order_id = 1;
			}
			sql = "insert into user_order (user_order.order_id,user_order.user_id,user_order.address_id,user_order.order_original_amount,user_order.order_settlemen_amount,user_order.order_coupon_id,user_order.order_request_arrival_time,user_order.order_state) values(?,?,?,?,?,?,?,?);" ;
			pst = conn.prepareStatement(sql);
			pst.setInt(1, order_id);
			pst.setInt(2, user_id);
			pst.setInt(3, address_id);
			pst.setFloat(4,original_amount );
			pst.setFloat(5, settle_amount);
			pst.setNull(6, java.sql.Types.INTEGER);
			pst.setNull(7, java.sql.Types.TIMESTAMP);
			pst.setNull(8, java.sql.Types.VARCHAR);
			pst.execute();
			
			//insert product_details into order_details 
			for(int i=0;i<list_cart.size();i++) {
				BeanProductInCart temp = list_cart.get(i);
				int order_details_id = -1;
				sql = "select max(order_details_id) from order_detail;";
				pst = conn.prepareStatement(sql);
				rs = pst.executeQuery();
				if(rs.next()) {
					order_details_id = rs.getInt(1);
				}else {
					order_details_id = 1;
				}
				sql = "insert into order_detail(order_detail.order_details_id,order_detail.product_id,order_detail.order_id,order_detail.order_details_amount,order_detail.order_details_price,order_detail.order_details_discount,order_detail.order_details_full_discount_id) values?,?,?,?,?,?,?);";
				pst = conn.prepareStatement(sql);
				pst.setInt(1, order_details_id);
				pst.setInt(2, temp.getProduct_id());
				pst.setInt(3, order_id);
				pst.setFloat(4, temp.getCart_product_count());
				pst.setFloat(5, temp.getPrice());
				pst.setNull(6, java.sql.Types.FLOAT);
				pst.setNull(7, java.sql.Types.INTEGER);
				pst.execute();
			}
				
			//detele product from current_cart and table cart
			sql = "delete from cart where user_id = ? and cart_is_selected = 1";
			pst = conn.prepareStatement(sql);
			pst.execute();
			rs.close();
			pst.close();
			
			for(int i=0;i<list_cart.size();i++) {
				BeanUser.currentCart.remove(list_cart.get(i));
			}
			
			conn.commit();
		}catch(SQLException e) {
			e.printStackTrace();
			throw new DbException(e);
		}finally {
			if(conn!=null) {
				try {
					conn.rollback();
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		
		return order;
	}
	
	@Override
	public BeanUser register(String user_name, String user_pwd, String user_sex, String user_email,
			String user_current_city, String user_telephone) throws BaseException {
		// TODO Auto-generated method stub
		
		BeanUser user = new BeanUser();
		Connection conn = null;
		String sql;
		java.sql.PreparedStatement pst;
		java.sql.ResultSet rs;
		try {
			conn = DBPool.getInstance().getConnection();
			
			sql = "select 1 from user_info where user_telephone = ? ;";
			pst = conn.prepareStatement(sql);
			pst.setString(1, user_telephone);
			rs = pst.executeQuery();
			if(rs.next()) {
				rs.close();
				pst.close();
				throw new BusinessException("telephone have been registed!");
			}
			rs.close();
			pst.close();
			
			sql = "insert into user_info  (user_name,user_sex,user_password,user_telephone,user_email,user_city,user_create_date) values(?,?,?,?,?,?,?); ";
			pst = conn.prepareStatement(sql);
			pst.setString(1, user_name);
			pst.setString(2, user_sex);
			pst.setString(3, user_pwd);
			pst.setString(4, user_telephone);
			pst.setString(5, user_email);
			pst.setString(6, user_current_city);
			pst.setTimestamp(7, new java.sql.Timestamp(System.currentTimeMillis()) );
			pst.execute();
			pst.close();
			
			sql = "select user_id from user_info where user_telephone = ?;";
			pst = conn.prepareStatement(sql);
			pst.setString(1, user_telephone);
			rs = pst.executeQuery();
			rs.next();
			
			user.setUser_id(rs.getInt(1));
			pst.close();
			rs.close();
			user.setUser_name(user_name);
			user.setUser_telephone(user_telephone);
			
		}catch(SQLException e) {
			e.printStackTrace();
			throw new DbException(e);
		}finally {
			if(conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return user;
	}

	@Override
	public void addCart(int product_id) throws BaseException {
		// TODO Auto-generated method stub
		//遍历当前购物车
		Connection conn=null;
		try{
			String sql;
			java.sql.PreparedStatement pst;
			java.sql.ResultSet rs;
			conn = DBPool.getInstance().getConnection();
			conn.setAutoCommit(false);
			boolean found = false;
			int i = 0;
			for(i=0 ;i < BeanUser.currentCart.size();i++) {
				if(product_id==BeanUser.currentCart.get(i).getProduct_id()) {
					if(BeanUser.currentCart.get(i).getCart_product_count()==20) {
						throw new BusinessException("该宝贝不能再多了哦");
					}
					BeanUser.currentCart.get(i).setCart_product_count(BeanUser.currentCart.get(i).getCart_product_count()+1);
					found = true;
					break;
				}
			}
			if(found) {
				sql = "update cart set cart_product_count = ? where cart_id = ? ;";
				pst = conn.prepareStatement(sql);
				pst.setFloat(1, BeanUser.currentCart.get(i).getCart_product_count());
				pst.setInt(2, BeanUser.currentCart.get(i).getCart_id());
				pst.execute();
				pst.close();
			}else {
				sql = "select max(cart_id) from cart ;";
				pst = conn.prepareStatement(sql);
				rs = pst.executeQuery();
				rs.close();
				int cart_id = -1;
				if(rs.next()) {
					cart_id = rs.getInt(1)+1;
				}else {
					cart_id = 1;
				}
				sql = "insert into cart (cart_id,product_id,user_id,cart_is_selected,cart_product_count) values(?,?,?,?,?);";
				pst = conn.prepareStatement(sql);
				pst.setInt(1, cart_id);
				pst.setInt(2, product_id);
				pst.setInt(3, BeanUser.currentLoginUser.getUser_id());
				pst.setBoolean(4, true);
				pst.setFloat(5, (float) 1.0);
				pst.execute();
				pst.close();
				BeanProductInCart p = new BeanProductInCart();
				p.setCart_id(cart_id);
				p.setProduct_id(product_id);
				p.setUser_id(BeanUser.currentLoginUser.getUser_id());
				p.setCart_selected(true);
				p.setCart_product_count((float) 1.0);
				BeanUser.currentCart.add(p);		
			}
			conn.commit();
		}catch(SQLException e) {
			e.printStackTrace();
			throw new DbException(e);
		}finally {
			if(conn!=null) {
				try {
					conn.rollback();
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}		
	}

	

	@Override
	public BeanUser login(String user_telephone, String pwd) throws BaseException {
		// TODO Auto-generated method stub
		BeanUser user = new BeanUser();
		Connection conn = null;
		
		try {
			
			conn = DBPool.getInstance().getConnection();
			String sql ;
			java.sql.PreparedStatement pst;
			java.sql.ResultSet rs;
			
			sql = "select user_id,user_name,user_telephone,user_password from user_info where user_telephone = ? ;";
			pst = conn.prepareStatement(sql);
			pst.setString(1, user_telephone);
			rs = pst.executeQuery();
			if(rs.next()) {
				user.setUser_id(rs.getInt(1));
				user.setUser_name(rs.getString(2));
				user.setUser_telephone(rs.getString(3));
				String user_pwd = rs.getString(4);
				if(!user_pwd.equals(pwd)) {
					rs.close();
					pst.close();
					throw new BusinessException("wrong password !");
				}
			}else {
				rs.close();
				pst.close();	
				throw new BusinessException("telephone not registed");
			}
			rs.close();
			pst.close();
			
		}catch (SQLException e) {
			e.printStackTrace();
			throw new DbException(e);
		}finally {
			if(conn!=null) {
				try {
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return user;
	}

	@Override
	public void delete(String telephone) throws BaseException {
		// TODO Auto-generated method stub
		Connection conn = null;
		try {
			
			conn = DBPool.getInstance().getConnection();
			conn.setAutoCommit(false);
			String sql;
			java.sql.PreparedStatement pst;
			sql = "delete from user_info where user_telephone = ?;";
			pst = conn.prepareStatement(sql);
			pst.setString(1, telephone);
			pst.execute();
			conn.commit();
		}catch (SQLException e) {
			e.printStackTrace();
			throw new DbException(e);
		}finally {
			if(conn!=null)
				try {
					conn.close();
				}catch (SQLException e) {
					e.printStackTrace();
				}
		}
	}

	@Override
	public ArrayList<BeanProductInCart> loadCart() throws BaseException {
		// TODO Auto-generated method stub
		BeanUser user= BeanUser.currentLoginUser;
		Connection conn = null;
		
		ArrayList<BeanProductInCart> cart = new ArrayList<BeanProductInCart>();
		BeanProductInCart p = null;
		try{
			conn = DBPool.getInstance().getConnection();
			String sql;
			java.sql.PreparedStatement pst;
			java.sql.ResultSet rs;
			sql = "select cart_id,product_id,user_id,cart_is_selected,cart_product_count from cart where user_id = ?; ";
			pst = conn.prepareStatement(sql);
			pst.setInt(1, user.getUser_id());
			rs = pst.executeQuery();
			while(rs.next()) {
				p = new BeanProductInCart();
				p.setCart_id(rs.getInt(1));
				p.setProduct_id(rs.getInt(2));
				p.setUser_id(rs.getInt(3));
				p.setCart_selected(rs.getBoolean(4));
				p.setCart_product_count(rs.getFloat(5));
				cart.add(p);
			}
			rs.close();
			pst.close();
		}catch(SQLException e) {
			e.printStackTrace();
			throw new DbException(e);
		}finally {
			if(conn!=null)
				try {
					conn.close();
				}catch (SQLException e) {
					e.printStackTrace();
				}
		}
		return null;
	}

	public void deleteProductFromCart(int product_id) throws BaseException {
		// TODO Auto-generated method stub
		Connection conn = null;
		
		try {
			conn = DBPool.getInstance().getConnection();
			conn.setAutoCommit(false);
			String sql;
			java.sql.PreparedStatement pst;
			java.sql.ResultSet rs;
			
			sql = "select 1 from cart where product_id =? and user_id = ? ; ";
			pst = conn.prepareStatement(sql);
			pst.setInt(1, product_id);
			pst.setInt(2, BeanUser.currentLoginUser.getUser_id());
			rs = pst.executeQuery();
			if(!rs.next()) {
				rs.close();
				pst.close();
				throw new BusinessException("商品不在购物车中，删除失败");
			}
			sql = "delete from cart where product_id = ? and user_id=? ;";
			pst = conn.prepareStatement(sql);
			pst.execute();
			pst.close();
			rs.close();
			BeanProductInCart p = null;
			for(int i=0;i<BeanUser.currentCart.size();i++) {
				p = BeanUser.currentCart.get(i);
				if(p.getProduct_id()==product_id) break;
			}
			if(!BeanUser.currentCart.remove(p)) {
				throw new BusinessException("删除购物车商品失败");
			}
			conn.commit();
		}catch(SQLException e) {
			e.printStackTrace();
			throw new DbException(e);
		}finally {
			if(conn!=null) {
				try {
					conn.rollback();
					conn.close();
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}	
	
	public BeanUser create_testUser() {
		BeanUser test = new BeanUser();
		test.setUser_id(0);
		test.setUser_name("test");
		test.setUser_telephone("0");
		return test;
	}
	public void set_test_cart() {
		ArrayList<BeanProductInCart> test_list = new ArrayList<BeanProductInCart>();
		BeanProductInCart p1= new BeanProductInCart();
		p1.setCart_id(1);
		p1.setCart_product_count(1);
		p1.setCart_selected(true);
		p1.setPrice(5);
		p1.setProduct_id(1);
		p1.setProduct_name("test_product1");
		p1.setUser_id(0);
		test_list.add(p1);
		BeanProductInCart p2= new BeanProductInCart();
		p2.setCart_id(2);
		p2.setCart_product_count(3);
		p2.setCart_selected(true);
		p2.setPrice(10);
		p2.setProduct_id(2);
		p2.setProduct_name("test_product1");
		p2.setUser_id(0);
		test_list.add(p2);
		BeanUser.currentCart = test_list;
		
	}
}
